package org.studiox.graph.runtime.service;

import org.apache.tinkerpop.gremlin.server.GraphGremlinServer;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.graphdb.server.JanusGraphSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.studiox.graph.runtime.config.RuntimeConfig;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
public class GremlinService {

  private static final Logger LOGGER = LoggerFactory.getLogger(GremlinService.class);

  @Autowired private RuntimeConfig runtimeConfig;

  @Autowired private GraphService graphService;

  private GraphGremlinServer graphGremlinServer;

  @PostConstruct
  public void init() {
    if (runtimeConfig.isGraphGremlinEnabled()) {
      JanusGraphSettings janusGraphSettings = GraphGremlinServer.createJanusGraphSettings();
      janusGraphSettings.port = runtimeConfig.getGraphGremlinPort();
      JanusGraph janusGraph = graphService.getJanusGraphInstance();
      graphGremlinServer = new GraphGremlinServer(janusGraphSettings, janusGraph);
      graphGremlinServer.start();
    }
  }

  @PreDestroy
  public void clean() {
    if (runtimeConfig.isGraphGremlinEnabled() && null != graphGremlinServer) {
      graphGremlinServer.stop();
    }
  }
}
